package id.co.shuba.spamobile.activities;

import java.util.Calendar;

import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;

import id.co.shuba.spamobile.App;
import id.co.shuba.spamobile.CustomSessionApplication;
import id.co.shuba.spamobile.LogoutReceiver;
import id.co.shuba.spamobile.R;
import id.co.shuba.spamobile.R.layout;
import id.co.shuba.spamobile.R.menu;
import id.co.shuba.spamobile.dialog.DatePickerFragment;
import id.co.shuba.spamobile.util.DialogUtil;
import id.co.shuba.spamobile.util.Str;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TimePicker;
import android.widget.Toast;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Intent;
import android.content.IntentFilter;

public class DownloadProspectActivity extends SherlockFragmentActivity {
	private static final int DATE_DIALOG_ID = 100;
	
	private EditText txtStartDate;
	private EditText txtEndDate;
	
	private EditText txtDate;
	private LogoutReceiver logoutReceiver;

	private void setUpLogoutReceiver() {
		IntentFilter intentFilter = new IntentFilter();
	    intentFilter.addAction("id.co.shuba.spamobile.ACTION_LOGOUT");
	    logoutReceiver = new LogoutReceiver(this);
	    registerReceiver(logoutReceiver, intentFilter);
	}
	
	@Override
	protected void onDestroy() {		
		unregisterReceiver(logoutReceiver);
		super.onDestroy();
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_download_prospect);
		setUpLogoutReceiver();
		
		txtStartDate = (EditText) findViewById(R.id.txtStartDate);
		txtEndDate = (EditText) findViewById(R.id.txtEndDate);

		Button btnDownload = (Button) findViewById(R.id.btnDownload);
		btnDownload.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				try {
					download();
				} catch (Exception e) {
					Toast.makeText(DownloadProspectActivity.this,
							e.getMessage(), Toast.LENGTH_LONG).show();
				}
			}
		});
	}

	public void download() throws Exception {
		String startDate = DialogUtil.changeFormat(txtStartDate.getText().toString());
		String endDate = DialogUtil.changeFormat(txtEndDate.getText().toString());

		if (!DialogUtil.isValid(startDate))
			throw new Exception("Invalid start date!");

		if (!DialogUtil.isValid(endDate))
			throw new Exception("Invalid end date!");

		Intent intent = new Intent(this, DownloadActivity.class);
		intent.putExtra(DownloadActivity.PARAMETER_OPTION,
				DownloadActivity.DOWNLOAD_PROSPECT_BY_DATE);
		intent.putExtra(DownloadActivity.PARAMETER_AUTO_START, true);
		//intent.putExtra(DownloadActivity.PARAMETER_EXIT_WHEN_DONE, true);
		intent.putExtra(DownloadActivity.PARAMETER_PROSPECT_START_DATE,
				startDate);
		intent.putExtra(DownloadActivity.PARAMETER_PROSPECT_END_DATE, endDate);

		startActivity(intent);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getSupportMenuInflater().inflate(R.menu.activity_download_prospect,
				menu);
		return true;
	}

	public void onDateDialogButtonClick(View v) {			
		switch (v.getId()) {
		case R.id.btnPickStartDate:
			txtDate = txtStartDate;
			break;
		case R.id.btnPickEndDate:
			txtDate = txtEndDate;
			break;
		}
		showDialog(DATE_DIALOG_ID);
	}
	
	private EditText getDateDisplay() {
		return txtDate;
	}
	
	 private OnDateSetListener dateSetListener = new OnDateSetListener() {
	        @Override
	        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
	        	String month = monthOfYear + 1 < 10? "0" + (monthOfYear +1) : String.valueOf(monthOfYear+1);
	        	String day = dayOfMonth < 10? "0" + dayOfMonth : String.valueOf(dayOfMonth);
	        	getDateDisplay().setText(
	                    new StringBuilder()                                     
	                        .append(day).append("-")
	                        .append(month).append("-")
	                        .append(year));            
	        }
	    };	    

	    @Override
	    protected Dialog onCreateDialog(int id) {
	        switch (id) {
	            case DATE_DIALOG_ID:
	                return createDatePicker();	      
	        }
	        return null;
	    }       
	    
	    private Dialog createDatePicker() {
	    	String date = txtDate.getText().toString();
	    	Calendar cal = Calendar.getInstance();
			int day = cal.get(Calendar.DAY_OF_MONTH);
			int month = cal.get(Calendar.MONTH);
			int year = cal.get(Calendar.YEAR);
			
			if (!Str.isNullOrEmpty(date)) {
				try {
					String[] values = date.split("-");
					year = Integer.parseInt(values[2]);
					month = Integer.parseInt(values[1]) -1;
					day = Integer.parseInt(values[0]);
				} catch (Exception e) {					
				}				
			}
			
			Dialog d = new DatePickerDialog(this, dateSetListener, year, month, day);
					
			return d;
	    }	    	  

	    @Override
	    protected void onPrepareDialog(int id, Dialog dialog) {
	        super.onPrepareDialog(id, dialog);
	        Calendar cal = Calendar.getInstance();
	        switch (id) {
	            case DATE_DIALOG_ID:
	            	String date = txtDate.getText().toString();            	
	        		int day = cal.get(Calendar.DAY_OF_MONTH);
	        		int month = cal.get(Calendar.MONTH);
	        		int year = cal.get(Calendar.YEAR);
	        		
	        		if (!Str.isNullOrEmpty(date)) {
	        			try {
	        				String[] values = date.split("-");
	        				year = Integer.parseInt(values[2]);
	        				month = Integer.parseInt(values[1]) -1;
	        				day = Integer.parseInt(values[0]);
	        			} catch (Exception e) {					
	        			}				
	        		}
	                ((DatePickerDialog) dialog).updateDate(year, month, day);
	                break;	           
	        }
	    }
	    
	    @Override
		public void onUserInteraction() {		
			super.onUserInteraction();
			((CustomSessionApplication) getApplication()).touch();
			
			if (App.DEBUG) {				
				Log.d("User Interaction", "User interaction to "+this.toString());			
			}
		}
}
